package com.yuanchu.store.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanchu.common.exception.YuanChuException;
import com.yuanchu.common.utils.DateFormatUtils;
import com.yuanchu.common.utils.PageResult;
import com.yuanchu.common.utils.PageUtils;
import com.yuanchu.common.utils.Query;
import com.yuanchu.store.dao.YoshopDeliveryDao;
import com.yuanchu.store.dto.DeliveryParamsDto;
import com.yuanchu.store.entity.YoshopDeliveryEntity;
import com.yuanchu.store.entity.YoshopDeliveryRuleEntity;
import com.yuanchu.store.service.YoshopDeliveryRuleService;
import com.yuanchu.store.service.YoshopDeliveryService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.Instant;
import java.util.List;
import java.util.Map;


@Service("yoshopDeliveryService")
public class YoshopDeliveryServiceImpl extends ServiceImpl<YoshopDeliveryDao, YoshopDeliveryEntity> implements YoshopDeliveryService {

    @Resource
    private YoshopDeliveryRuleService deliveryRuleService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<YoshopDeliveryEntity> page = this.page(
                new Query<YoshopDeliveryEntity>().getPage(params),
                new QueryWrapper<YoshopDeliveryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<YoshopDeliveryEntity> queryGoodsDelivery(Map<String, Object> params) {

        return this.list();
    }

    @Override
    public YoshopDeliveryEntity queryDeliveryById(Integer deliveryId) {
        return this.getById(deliveryId);

    }

    @Override
    public YoshopDeliveryRuleEntity queryDeliveryBigDecimalById(Integer deliveryId) {
        YoshopDeliveryEntity delivery = this.getById(deliveryId);
        YoshopDeliveryRuleEntity deliveryRule = deliveryRuleService.getOne(new QueryWrapper<YoshopDeliveryRuleEntity>().eq("delivery_id", deliveryId));
        // if (deliveryRule != null) {
        //     return deliveryRule.getFirstFee();
        // }
        deliveryRule.setMethod(delivery.getMethod());
        return deliveryRule;
    }

    @Override
    public PageResult<YoshopDeliveryEntity> queryDeliveryList(Integer page, String search) {
        LambdaQueryWrapper<YoshopDeliveryEntity> lqw = new LambdaQueryWrapper<>();
        lqw.eq(YoshopDeliveryEntity::getIsDelete, 0);
        lqw.like(StringUtils.isNotEmpty(search), YoshopDeliveryEntity::getName, search);
        lqw.orderByDesc(YoshopDeliveryEntity::getSort);
        Page<YoshopDeliveryEntity> pageResult = this.page(new Page<>(page, 15), lqw);
        List<YoshopDeliveryEntity> records = pageResult.getRecords();
        records.forEach(record -> {
            record.setCreateTime(DateFormatUtils.formatDatetime(record.getCreateTime()));
        });
        return PageResult.formatPageResult(records, page, 15, pageResult.getTotal());
    }

    @Override
    @Transactional
    public void saveDelivery(DeliveryParamsDto params) {
        YoshopDeliveryEntity delivery = new YoshopDeliveryEntity();
        DeliveryParamsDto.ExpressForm form = params.getForm();
        BeanUtils.copyProperties(form, delivery);
        delivery.setStoreId(10001);
        delivery.setCreateTime(String.valueOf(Instant.now().toEpochMilli()/1000));
        delivery.setUpdateTime(String.valueOf(Instant.now().toEpochMilli()/1000));
        boolean save = this.save(delivery);
        if (!save){
            throw new YuanChuException("保存失败");
        }
        List<DeliveryParamsDto.RulesForm> rules = form.getRules();
        rules.forEach(rule -> {
            YoshopDeliveryRuleEntity deliveryRule = new YoshopDeliveryRuleEntity();
            BeanUtils.copyProperties(rule, deliveryRule);
            deliveryRule.setFirst(rule.getFirst());
            deliveryRule.setFirstFee(rule.getFirstFee());
            deliveryRule.setDeliveryId(delivery.getDeliveryId());
            deliveryRule.setRegion(JSON.toJSONString(rule.getRegion()));
            deliveryRule.setRegionText(JSON.toJSONString(rule.getRegionText()));
            deliveryRule.setCreateTime(String.valueOf(Instant.now().toEpochMilli()/1000));
            boolean save1 = deliveryRuleService.save(deliveryRule);
            if (!save1){
                throw new YuanChuException("保存失败");
            }
        });


    }

    @Override
    @Transactional
    public void updateDelivery(DeliveryParamsDto params) {
        Integer deliveryId = params.getDeliveryId();
        YoshopDeliveryEntity delivery = this.getById(deliveryId);
        if (delivery == null){
            throw new YuanChuException("该配送模板不存在");
        }
        BeanUtils.copyProperties(params.getForm(), delivery);
        delivery.setDeliveryId(deliveryId);
        boolean update = this.updateById(delivery);
        if (!update){
            throw new YuanChuException("修改失败");
        }
        boolean deliveryId1 = deliveryRuleService.remove(new QueryWrapper<YoshopDeliveryRuleEntity>().eq("delivery_id", deliveryId));
        if (!deliveryId1){
            throw new YuanChuException("修改失败");
        }
        List<DeliveryParamsDto.RulesForm> rules = params.getForm().getRules();

        rules.forEach(rule -> {
            YoshopDeliveryRuleEntity deliveryRule = new YoshopDeliveryRuleEntity();
            BeanUtils.copyProperties(rule, deliveryRule);
            deliveryRule.setDeliveryId(deliveryId);
            deliveryRule.setRegion(JSON.toJSONString(rule.getRegion()));
            deliveryRule.setRegionText(JSON.toJSONString(rule.getRegionText()));
            deliveryRule.setStoreId(1001);
            boolean save1 = deliveryRuleService.save(deliveryRule);
            if (!save1){
                throw new YuanChuException("修改失败");
            }
        });
    }

    @Override
    @Transactional
    public void deleteDelivery(Integer deliveryId) {
        boolean update = this.update(new UpdateWrapper<YoshopDeliveryEntity>().eq("delivery_id", deliveryId)
                .set("is_delete", 1));
        if (!update){
            throw new YuanChuException("删除失败");
        }

        // boolean delete = this.removeById(deliveryId);
        // if (!delete){
        //     throw new YuanChuException("删除失败");
        // }
        // boolean deliveryId1 = deliveryRuleService.remove(new QueryWrapper<YoshopDeliveryRuleEntity>().eq("delivery_id", deliveryId));
        // if (!deliveryId1){
        //     throw new YuanChuException("删除失败");
        // }
    }

    @Override
    public YoshopDeliveryEntity queryExpressDetail(Integer deliveryId) {
        YoshopDeliveryEntity delivery = this.getById(deliveryId);
        if (delivery == null){
            throw new YuanChuException("该配送模板不存在");
        }
        List<DeliveryParamsDto.RulesForm> rules = deliveryRuleService.queryRuleList(deliveryId);

        delivery.setRule(rules);
        delivery.setCreateTime(DateFormatUtils.formatDatetime(delivery.getCreateTime()));
        return delivery;
    }


}